package com.loveyukari.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.loveyukari.dao.LiwuDao;
import com.loveyukari.model.Liwu;

/**
*
*yangshaohua
*2016年12月13日下午3:49:46
**/

@Repository
public class JdbcLiwuDao extends BaseDao implements LiwuDao{

	public void insertLiwu(Liwu liwu) {
		String sql = "insert into liwu(uid,gfid,hits,give_time) values(?,?,?,?)";
		this.getJdbcTemplate().update(sql, liwu.getUid(),liwu.getGfid(),liwu.getHits(),liwu.getGiveTime());
	}

	public void updateLiwu(Liwu liwu) {
		String sql = "update liwu set hits=?,give_time=?,status=? where id = ?";
		this.getJdbcTemplate().update(sql, liwu.getHits(),liwu.getGiveTime(),liwu.getStatus(),liwu.getId());
	}

	public Liwu selectLiwuByUidAndGfid(Integer uid, Integer gfid) {
		String sql = "select * from liwu where uid=? and gfid = ? and status = 0 order by id desc limit 1";
		List<Liwu> list = this.getJdbcTemplate().query(sql, new LiwuRowMapper(), uid,gfid);
		if (list == null || list.isEmpty()){
			return null;
		} else {
			return list.get(0);
		}
	}
	private class LiwuRowMapper implements RowMapper<Liwu>{

		public Liwu mapRow(ResultSet rs, int rowNum) throws SQLException {
			Liwu liwu = new Liwu();
			liwu.setId(rs.getInt("id"));
			liwu.setGfid(rs.getInt("gfid"));
			liwu.setGiveTime(rs.getTimestamp("give_time"));
			liwu.setHits(rs.getInt("hits"));
			liwu.setStatus(rs.getInt("status"));
			liwu.setUid(rs.getInt("uid"));
			return liwu;
		}
		
	}
	public List<Liwu> selectLiwuByRead(int size) {
		String sql = "select * from liwu where status = 0 order by give_time desc";
		if (size > 0){
			sql += " limit ?";
			return this.getJdbcTemplate().query(sql, new LiwuRowMapper(),size);
		}
		List<Liwu> list = this.getJdbcTemplate().query(sql, new LiwuRowMapper());
		return list;
	}

	public Liwu selectLiwuById(int id) {
		String sql = "select * from liwu where id = ?";
		List<Liwu> list = this.getJdbcTemplate().query(sql, new LiwuRowMapper(),id);
		if (list.isEmpty()){
			return null;
		} else {
			return list.get(0);
		}
	}
	
	public void updateLiwuStatus(int status,List<Integer> ids){
		String sql = "update liwu set status = ? where id = ?";
		List<Object[]> params = new ArrayList<Object[]>();
		for (Integer id : ids) {
			Object[] param = new Object[2];
			param[0]=status;
			param[1]=id;
			params.add(param);
		}
		this.getJdbcTemplate().batchUpdate(sql, params);
	}

	public List<Liwu> selectLiwuByDate(Date date) {
		String sql = "select * from liwu where (give_time > ?) or (gfid <= 3 and give_time between '20170206' and '20170211')";
		List<Liwu> list = this.getJdbcTemplate().query(sql, new LiwuRowMapper(),date);
		return list;
	}

}
